package com.atguigu.chapter11;

import com.atguigu.chapter05.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;

/**
 * TODO
 *
 * @author cjp
 * @version 1.0
 * @date 2021/3/12 9:30
 */
public class Flink11_TimeChracteristic_EventTime {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        // 切分
                        String[] line = value.split(",");
                        return new WaterSensor(line[0], Long.valueOf(line[1]), Integer.valueOf(line[2]));

                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((value, ts) -> value.getTs() * 1000L)
                );


        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        // TODO TableAPI 指定 时间时间： 在 流 转换成 表 的时候
        // 方式一： 在额外字段指定 事件时间，它的来源是 流上指定了 事件时间的提取
        // 方式二： 在已有字段指定，它的来源也是 流上指定了 事件时间的提取，但是不推荐，因为数据格式被改变了
        Table sensorTable = tableEnv.fromDataStream(sensorDS,
                $("id"),
                $("ts"),
//                $("ts").rowtime(),
                $("vc"),
                $("et").rowtime()
        );

//        sensorTable.printSchema();

//        sensorTable.execute().print();






        // TODO SQL 指定 处理时间：
        tableEnv.executeSql("create table sensor(" +
                "id string," +
                "ts bigint," +
                "vc int," +
                "t as to_timestamp(from_unixtime(ts/1000,'yyyy-MM-dd HH:mm:ss'))," +
                "watermark for t as t - interval '5' second) " +
                "with (" +
                "'connector' = 'filesystem'," +
                "'path' = 'input/sensor.csv'," +
                "'format' = 'csv'" +
                ")");
//
        tableEnv.executeSql("select * from sensor").print();






        env.execute();
    }
}
